package com.java.simple.study.juc.p7;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhoujunlin
 * @date 2022年08月24日 22:35
 * @desc
 */
public class TestReadWriteLock {

    public static void main(String[] args) {
        DataContainer dataContainer = new DataContainer();
        new Thread(() -> {
            dataContainer.read();
        }, "t1").start();

        Sleeper.sleep(0.1);

        new Thread(() -> {
            dataContainer.write();
        }, "t2").start();
    }

}

@Slf4j(topic = "c.DataContainer")
class DataContainer {
    private Object data;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();

    public Object read() {
        log.debug("获取读锁...");
        readLock.lock();
        try {
            log.debug("读取");
            Sleeper.sleep(1);
            return data;
        } finally {
            log.debug("释放读锁...");
            readLock.unlock();
        }
    }

    public void write() {
        log.debug("获取写锁...");
        writeLock.lock();
        try {
            log.debug("写入");
            Sleeper.sleep(1);
        } finally {
            log.debug("释放写锁...");
            writeLock.unlock();
        }
    }
}

class CachedData {
    Object data;
    // 是否有效 如果失效 需要重新计算data
    volatile boolean cacheValid;
    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    void processCachedData(Object newData) {
        rwl.readLock().lock();
        if (!cacheValid) {
            // 获取写锁前必须释放读锁  因为无法升级
            rwl.readLock().unlock();
            // 加写锁
            rwl.writeLock().lock();
            try {
                // 双重判断校验  判断是否有其他线程已经获取了写锁更新了缓存 避免重复更新
                if (!cacheValid) {
                    data = newData;
                    cacheValid = true;
                }
                // 降级为读锁 释放写锁  这样能够让其他线程读取缓存
                rwl.readLock().lock();
            } finally {
                rwl.writeLock().unlock();
            }
        }

        // 自己用完数据  释放读锁
        try {
            use(data);
        } finally {
            rwl.readLock().unlock();
        }
    }

    private void use(Object data) {
    }

}






